const db = require('../db');

class TreeMenuModel {
    // 创建
    static async create(name, treeJson) {
        const [result] = await db.execute(
            "INSERT INTO tree_menu (name, tree, status) VALUES (?, ?, 1)",
            [name, JSON.stringify(treeJson)]
        );
        const [rows] = await db.execute("SELECT * FROM tree_menu WHERE id = ?", [result.insertId]);
        const menu = rows[0];
        return {
            id: menu.id,
            name: menu.name,
            tree: JSON.parse(menu.tree),
            status: menu.status,
            created_at: menu.created_at,
            updated_at: menu.updated_at
        };
    }

    // 查询所有（只查正常或禁用的，不查已软删除的）
    static async findAll() {
        const [rows] = await db.execute("SELECT * FROM tree_menu WHERE status != 2");
        return rows.map(row => ({
            ...row,
            tree: JSON.parse(row.tree)
        }));
    }

    // 根据 id 查询（忽略被软删除的）
    static async findById(id) {
        const [rows] = await db.execute("SELECT * FROM tree_menu WHERE id = ? AND status != 2", [id]);
        if (rows.length === 0) return null;
        return {
            ...rows[0],
            tree: JSON.parse(rows[0].tree)
        };
    }

    // 更新
    static async update(id, name, treeJson, status = 1) {
        const [result] = await db.execute(
            "UPDATE tree_menu SET name = ?, tree = ?, status = ? WHERE id = ? AND status != 2",
            [name, JSON.stringify(treeJson), status, id]
        );
        return result.affectedRows > 0;
    }

    // 软删除
    static async delete(id) {
        const [result] = await db.execute(
            "UPDATE tree_menu SET status = 2 WHERE id = ?",
            [id]
        );
        return result.affectedRows > 0;
    }
}

module.exports = TreeMenuModel;
